package com.fanly.weixin.netty.lock.decoder;

import com.fanly.weixin.netty.lock.LockTcpServer;
import com.fanly.weixin.netty.lock.protocol.ProtocolModel;
import com.fanly.weixin.netty.lock.service.DataParseService;
import com.fanly.weixin.utils.ByteCastUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 可用网络调试助手、Modbus Poll进行调试
 */
@Slf4j
@Component
public class DecoderHandler extends SimpleChannelInboundHandler {

    private static DecoderHandler DecoderHandler;

    @Autowired
    private DataParseService dataParseService;

    @PostConstruct
    public void init() {
        DecoderHandler = this;
        DecoderHandler.dataParseService = this.dataParseService;
    }

    /**
     * 读取客户端传过来的数据
     * 发送到目标，比如redis，websocket，涛思数据库等
     *
     * @param ctx           the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *                      belongs to
     * @param msg           the message to handle
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    	try {
    		ByteBuf buffer = (ByteBuf) msg;
            if (buffer == null) {
            	log.error("DecoderHandler-channelRead0-{}-接收到客户端遥测数据为空",ctx.channel().remoteAddress());
                return;
            }
            String string= ByteBufUtil.hexDump(buffer).toUpperCase();
            log.info("DecoderHandler-接收数据-channelRead0-{}-{}"+ctx.channel().remoteAddress(),string);
            String pushData = DecoderHandler.dataParseService.realTimeDataParseAndPushData(ctx,string);
            log.info("DecoderHandler-发送数据-channelRead0--{}-{}"+ctx.channel().remoteAddress(),pushData);
            String sendData = ByteCastUtil.hexToAscii(pushData);
            this.replyMessage(ctx, sendData);
            buffer.clear();
		} catch (Exception e) {
            log.error("DecoderHandler-channelRead0-{}, 处理异常：{}",ctx.channel().remoteAddress(),e.fillInStackTrace());
		}
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        if (cause instanceof Exception) {
            log.error("DecoderHandler-exceptionCaught--异常捕获");
            cause.printStackTrace();
//            ctx.close();
        }
    }

    /**
     *
     * channel 通道 action 活跃
     * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
		Channel channel = ctx.channel();
        LockTcpServer.deviceAdd(ctx.channel());
        log.info("DecoderHandler-channelActive netty-->TCP客户端服务上线："+ channel.remoteAddress());
    }

    /**
     * channel 通道 action 不活跃
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        LockTcpServer.deviceRemove(ctx.channel());
//        ctx.close();
        log.error("DecoderHandler-exceptionCaught netty-->TCP客户端服务下线：" + channel.remoteAddress());
    }

    /**
     * 读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        log.error("DecoderHandler-channelReadComplete 接收到客户端信息完成");
        ctx.flush();
    }
    /**
     * 回复消息
     * @param ctx
     * @param message
     */
    public void replyMessage(ChannelHandlerContext ctx, String message){
        ProtocolModel res = new ProtocolModel();
        res.setData(message.getBytes());
        ctx.writeAndFlush(res);
    }
}